const errorType = require('../contants/error-types');
const service = require('../service/user.service');
const md5password = require('../utils/password_handle');

const verifyUser = async (ctx, next) => {
  //1.獲取用戶名和密碼
  const { name, password } = ctx.request.body;
  //2.判斷用戶名和密碼不能爲空
  if (!name || !password) {
    const error = new Error(errorType.NAME_OR_PASSWORD_IS_REQUIRED);
    return ctx.app.emit('error', error, ctx);
  }
  //3.判斷這次注冊的用戶名是沒有注冊過的
  const result = await service.getUserByName(name);
  if (result.length) {
    const error = new Error(errorType.USER_ALREADY_EXISTS);
    return ctx.app.emit('error', error, ctx);
  }
  await next();
};

const handlePassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  ctx.request.body.password = md5password(password);
  await next();
};

module.exports = {
  verifyUser,
  handlePassword,
};
